const { typeOf, needParam } = require("./base");
const dictMap = require("../dicts");

module.exports = {
  /**
   * 获取字典
   * @param {string|object} name 字典名或字典对象
   */
  getDict(name = needParam()) {
    const t = typeOf(name);
    if (t === "String") {
      const map = dictMap[name];
      if (!map) throw new Error(`不存在字典${name}`);
      return map;
    }
    if (t === "Object") return name;
    throw new Error(`暂未处理此类型：${t}`);
  },
  /**
   * 获取字典某个文本（字符串）
   * @param {string|object} name 字典名或字典对象
   * @param {string | number} val 字典值
   */
  getLabel(name = needParam(), val = needParam()) {
    return module.exports.getDict(name)[val] ?? "";
  },
  /**
   * 获取字典所有文本（数组）
   *  @param {string|object} name 字典名或字典对象
   */
  getLabels(name = needParam()) {
    const { getDict } = module.exports;
    return Object.keys(getDict(name)).map(it => Number(it));
  },
  /**
   * 获取字典的所有值（数组）
   *  @param {string|object} name 字典名或字典对象
   */
  getValues(name = needParam()) {
    const { getDict } = module.exports;
    return Object.keys(getDict(name)).map(it => Number(it));
  },
  /**
   * 获取枚举对象文本
   * @param {object} 字典名或字典对象，例：0未知 1男 2女
   * @returns {string}
   */
  getEnumText(enums = needParam(), joinChar = ["", " "]) {
    const [char1, char2] = joinChar;
    return Object.entries(enums)
      .map(arr => arr.join(char1))
      .join(char2);
  },
  /**
   * 获取下拉项
   * @param {string} name 字典名或字典对象
   */
  getOptions(name = needParam()) {
    const map = module.exports.getDict(name);
    return Object.keys(map).map(key => {
      const val = Number(key);
      return { label: map[key], value: isNaN(val) ? key : val };
    });
  },
  /**
   * 判断是否是合法的枚举值
   * @param {number} val val值
   * @param {string|object} name 字典名或字典对象
   * @returns {boolean}
   */
  isValidValue(val = needParam(), name = needParam()) {
    const vals = module.exports.getValues(name);
    if (!vals.includes(val)) throw new Error(`值应为：${vals.join(", ")}之一，实为：${val}`);
    return true;
  },
  /**
   * 获取级联地址文本
   */
  // getCascadeText(type, ids = [0, 0, 0]) {
  //   if (type === "Region") {
  //     const [pId, cId, aId] = ids;
  //     const pItem = allAddress.find((it) => it.id === pId);
  //     const cItem = pItem?.city.find((it) => it.id === cId);
  //     const aItem = cItem?.area.find((it) => it.id === aId);
  //     return `${pItem?.name}${cItem?.name}${aItem?.name ?? ""}`;
  //   } else {
  //     return "-";
  //   }
  // },
};
